<template>
  <view :class="[theme, 'oh']">
    <navigator v-if="showBack" open-type="navigateBack" hover-class="tap-hover"
      class="back ai-center jc-center br-50percent">
      <u-icon size="36" color="#fff" name="arrow-leftward" />
    </navigator>
    <view class="fd-row ai-center jc-center"
      style="margin: calc(var(--window-top) + var(--status-bar-height)) 30rpx 30rpx; height: 44px;">
      <view class="relative fd-row ai-center">
        <view @click="changeCurrentTab(index)" v-for="(item, index) in tabs.list" :key="index" class="relative mr-60">
          <text :class="[index === tabs.current ? 'color-3' : 'color-9', `relative fw-700 fs-36`]" :style="{
            textShadow: index === tabs.current ? `0 0 8rpx rgba(59, 134, 246, 0.6)` : `unset`,
            zIndex: 1,
            transition: `all 0.3s ease-in-out`
          }">
            {{ item.name }}
          </text>
        </view>
        <view class="absolute bottom-0 height-8 br-30 bg-23 width-120"
          :style="{ transition: `left 0.3s ease-in-out`, transform: `translateX(-60%)`, left: `calc(100% / ${tabs.list.length} / 2 + 100% / ${tabs.list.length} * ${tabs.current})`, }" />
      </view>
    </view>

    <view class="bg-2 br-40 oh" style="margin: 0 20rpx;">
      <u-image width="100%" height="840" radius="40" :src="poster" />
      <view class="fd-row bg-2 p-40">
        <view class="f1 oh mr-12">
          <text class="fs-28 fw-700">
            <text class="color-5" style="text-decoration: underline;">{{ userInfo.nickname || "-" }}</text>
            <text>的{{ tabs.list[tabs.current].name }}</text>
          </text>
          <label class="mt-20 ai-baseline">
            <u-image width="50" height="50" src="/static/img/icon-code.svg" />
            <text class="ml-28 fw-700 ellipsis" style="font-size: 64rpx;">
              {{ userInfo[tabs.list[tabs.current].field] || "-" }}
            </text>
          </label>
          <text class="mt-20 color-placeholder">扫码注册玩转星球，让我们一起崛起！</text>
        </view>
        <view class="relative ai-center jc-center">
          <l-painter :css="`width: 150rpx; height: 150rpx; `" isCanvasToTempFilePath>
            <l-painter-qrcode css="width: 100%; height: 100%;"
              :text="`${$config.URL_ASSETS}${$config.ASSETS_PREFIX}/?timestamp=${Date.now()}#/pages/client/auth/register?code=${userInfo[tabs.list[tabs.current].field] || '-'}`" />
          </l-painter>
        </view>
      </view>
    </view>

    <view class="fd-row m-60 oh">
      <button @click="saveImage" hover-class="tap-hover" class="f1 mr-20 fs-32 br-50 border-none color-2 bg-6"
        plain>保存图片</button>
      <button @click="copyText(userInfo.code)" hover-class="tap-hover"
        class="f1 ml-20 fs-32 br-50 border-none color-2 bg-10" plain>
        复制{{ tabs.list[tabs.current].name }}
      </button>
    </view>
    <l-painter v-if="poster" custom-style="position: fixed; top: 0; left: 200%;" :css="`width: 750rpx; height: 1060rpx;`"
      isCanvasToTempFilePath ref="painter">
      <l-painter-image :src="poster" css="width: 100%; height: 840rpx; object-fit: cover;" />
      <l-painter-view css="position: absolute; background-color: #fff; width: 100%; bottom: 0; left: 0; padding: 30rpx;">
        <l-painter-view css="width: 450rpx; display: inline-block;">
          <l-painter-text :text="`${userInfo.nickname || '-'}`"
            css="color: #3b86f6; font-size: 28rpx; font-weight: bold; text-decoration: underline;" />
          <l-painter-text :text="`的${tabs.list[tabs.current].name}`"
            css="color: #333; font-size: 28rpx; font-weight: bold;" />

          <l-painter-view css="width: 450rpx; display: inline-block; margin-top: 20rpx;">
            <l-painter-image src="/static/img/icon-code.svg" css="width: 50rpx; height: 50rpx; border-radius: 50%;" />
            <l-painter-text :text="userInfo[tabs.list[tabs.current].field]"
              css="margin-left: 28rpx; line-height: 64rpx; color: #333; font-size: 64rpx; font-weight: bold;" />
          </l-painter-view>

          <l-painter-text text="扫码注册玩转星球，让我们一起崛起吧！"
            css="display: block; margin-top: 20rpx; color: #999; font-size: 24rpx;" />
        </l-painter-view>

        <l-painter-view css="position: relative; display: inline-block; margin-left: 60rpx; margin-top: 6rpx;">
          <!-- #ifdef H5 || APP-PLUS -->
          <l-painter-qrcode v-if="1" css="margin-left: 30rpx; width: 150rpx; height: 150rpx;"
            :text="`${$config.URL_ASSETS}${$config.ASSETS_PREFIX}/?timestamp=${Date.now()}#/pages/client/auth/register?code=${userInfo[tabs.list[tabs.current].field] || '-'}&share_mode=1`" />
          <!--  #endif -->
          <!-- #ifdef MP -->
          <l-painter-image src="/static/logo.png" css="margin-left: 32rpx; width: 180rpx; height: 180rpx;" />
          <!--  #endif -->
        </l-painter-view>
      </l-painter-view>
    </l-painter>
  </view>
</template>

<script lang="ts" setup>

import { useMapState } from "@/common/libs/store";
import { debounce, getClient } from "@/common/libs/utils";
import { onLoad } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";

const { theme } = useMapState(["theme"]);
const { $config = {} } = getApp().globalData || {};
const showBack = ref(false);

const tabs = reactive({
  list: [
    { name: "邀请码", field: "code" },
    { name: "排线码", field: "px_code" },
  ],
  current: 0
});
const painter = ref<any>(null);
const userInfo = ref<AnyObject>({
  avatar: "/static/img/default-avatar.png"
});

const poster = $config.URL_STATIC + "/img/poster.png";

onLoad(() => {
  showBack.value = getCurrentPages().length > 1;
  uni.showToast({ icon: "loading" });
  uni.request({
    url: $config.API_USER_INFO_GET,
    success({ data }: any) {
      userInfo.value = data;
      uni.hideToast();
    },
  });
});

const changeCurrentTab = (index: number) => {
  if (tabs.current === index) return;
  tabs.current = index;
}

const copyText = debounce((data: string) => {
  if (!data) {
    uni.showToast({ title: "复制失败", icon: "error" });
    return;
  }
  uni.setClipboardData({ data, showToast: true });
});

const saveImage = debounce(() => {
  uni.showToast({ mask: true, icon: "loading" });
  painter.value.canvasToTempFilePath({
    fileType: "png",
    quality: 100,
    success: ({ tempFilePath }: any) => {
      switch (getClient()) {
        case 1:
        case 2:
        case 3:
        case 4:
          const arr = tempFilePath.split(',');
          const bytes = window.atob(arr[1]);
          const ab = new ArrayBuffer(bytes.length);
          const ia = new Uint8Array(ab);
          for (let i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
          }
          const blob = new Blob([ab], { type: 'application/octet-stream' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `poster.png`;
          a.click();
          URL.revokeObjectURL(url);
          break;
        case 5:
        case 6:
          uni.showToast({ mask: true, icon: "loading" });
          uni.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success: res => {
              uni.showToast({ title: "图片已保存至相册", icon: "none" });
            }
          });
          break;
        default:
          break;
      }
      uni.hideToast();
    }
  });
});

</script>

<style lang="scss">
.back {
  position: fixed;
  left: calc(var(--window-left) + 3px);
  top: calc(7px + var(--window-top) + var(--status-bar-height));
  height: 32px;
  width: 32px;
  overflow: hidden;
  box-sizing: border-box;
  z-index: 998;
  background-color: rgba(0, 0, 0, 0.5);
  transition-property: all;
}
</style>